﻿API_KEY = "F9325D4E4DCCCB2C02F86E4B9A1BAFCA"
IMAGE_LOGIN_URL = "http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_large_border.png"
PROVIDER_URL = "http://steamcommunity.com/openid"
MATCHES_PER_PAGE = 1

import webapp2
import google.appengine.ext.webapp.template as template
import urllib
import json
import utils
from google.appengine.api import users
import models

class MainHandler(webapp2.RequestHandler):
    def get(self):
        user = utils.getUser(self.request.get('viewer_id'))
        if user:
            userObject = utils.GetUserInfo(user.steamID, API_KEY)
            http = urllib.urlopen("http://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/v1?key={0}&format=json&account_id={1}".format(API_KEY, user.steamID))
            json_object = json.loads(http.read())
            page = int(self.request.get('page') or 0)
            pages = range(utils.CalculatePageSize(json_object['result']['total_results'], MATCHES_PER_PAGE))
            matches = [match['match_id'] for match in json_object['result']['matches']]
            matches = utils.GetMatchesInfo(matches[page*MATCHES_PER_PAGE:(page*MATCHES_PER_PAGE)+MATCHES_PER_PAGE], API_KEY)
            links = [["Матчи", "/?{0}".format(self.request.query_string), True],
                     ["Друзья", "/friends?{0}".format(self.request.query_string)],
                     ["Выйти", users.create_logout_url("/logout?{0}".format(self.request.query_string))]]
            self.response.write(template.render("matches.html", 
                                    {"user" : userObject,
                                     "matches" : matches,
                                     "pages" : pages,
                                     "query_string" : self.request.query_string,
                                     "current_page" : page,
                                     "links" : links}))
            
        else:
            self.redirect("/login?{0}".format(self.request.query_string))
            
class MatchHandler(webapp2.RequestHandler):
    def get(self):
        user = utils.getUser(self.request.get('viewer_id'))
        if user:
            if self.request.get('match_id'):
                userObject = utils.GetUserInfo(user.steamID, API_KEY)
                links = [["Матчи", "/?{0}".format(self.request.query_string), True],
                         ["Друзья", "/friends?{0}".format(self.request.query_string)],
                         ["Выйти", users.create_logout_url("/logout?{0}".format(self.request.query_string))]]
                matchInfo = utils.GetMatchesInfo((self.request.get('match_id'),), API_KEY)
                self.response.write(template.render("match.html", 
                                        {"user" : userObject,
                                         "query_string" : self.request.query_string,
                                         "links" : links,
                                         "match" : matchInfo[0]}))
            else:
                self.response.redirect('/?{0}'.format(self.request.query_string))
        else:
            self.redirect("/login?{0}".format(self.request.query_string))
            
            
class LoginHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            userid = str(user.federated_identity().split("/")[-1:][0])
            models.User(vkID = int(self.request.get("viewer_id")), steamID = int(userid), key_name=self.request.get("viewer_id")).put()
            self.redirect("/?{0}".format(self.request.query_string))
        else:
            self.response.write(template.render("login.html", 
                                                {"login_url" : users.create_login_url("/login?{0}".format(self.request.query_string), federated_identity = PROVIDER_URL),
                                                 "login_image_url" : IMAGE_LOGIN_URL}))
            
            
class FriendsHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            userid = str(user.federated_identity().split("/")[-1:])
            http = urllib.urlopen("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={0}&format=json&steamids={1}".format(API_KEY, userid))
            json_object = json.loads(http.read())
            avatar_url = json_object['response']['players'][0]['avatar']
            nickname = json_object['response']['players'][0]['personaname']
            links = [["Матчи", "/"], ["Друзья", "/friends", True], ["Выйти", users.create_logout_url("/")]]
            self.response.write(template.render("friends.html", 
                                        {"nickname" : nickname, 
                                         "avatar_url" : avatar_url,
                                         "links" : links}))
        else:
            self.redirect("/login")
        
app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/login', LoginHandler),
    ('/friends', FriendsHandler),
    ('/match', MatchHandler)
], debug=True)
